/**
 * 事件选择器（下拉）
 * 默认显示50条，可通过搜索关键词更新下拉列表
 * 事件id和名称双向绑定
 * 
 * 陶俊（taojun1994@gmail.com）
 * 2022-04-28
 */
import { defineComponent, ref, reactive, computed, watch, onMounted } from "vue";
import { getEventPageList as listAPI } from "@/api/event";

export default defineComponent({
  name: "EventSelect",
  emits: ['update:modelValue', 'update:name'],
  props: {
    // 事件id
    modelValue: {
      type: String,
      default: ''
    },
    // 事件名称
    name: {
      type: String,
      default: ''
    }
  },
  setup (props, { emit }) {
    const options = ref([])
    const loading = ref(false)
    const query = reactive({
      evtName: '',
      current: 1,
      size: 50
    })
    const data = computed({
      get: () => props.modelValue,
      set: (val) => {
        if (!val) {
          emit('update:modelValue', '')
          emit('update:name', '')
        }
        emit('update:modelValue', val)
        emit('update:name', options.value.find(item => item.id === val).evtName)
      }
    })

    // 获取列表
    const getList = async () => {
      loading.value = true
      const res = await listAPI({ ...query })
      loading.value = false
      if (res.status === 200) {
        options.value = res.data.list
      }
    }

    // 
    const remoteMethod = (text) => {
      query.evtName = text
      getList()
    }

    onMounted(() => {
      getList()
    })

    watch(() => props.name, (val) => {
      remoteMethod(val)
    })

    return () => (
      <el-select
        v-model={data.value}
        filterable
        clearable
        remote
        reserve-keyword
        placeholder="搜索关键词"
        remote-method={remoteMethod}
        loading={loading.value}
        style={{ width: '100%' }}
      >
        {
          options.value.map(item => (
            <el-option
              key={item.id}
              label={item.evtName}
              value={item.id}
            />
          ))
        }
      </el-select>
    )
  }
})